/**
 * @file CheckModal.tsx
 * @author zhaoli
 */

import * as React from 'react';
import { inject, observer } from "mobx-react";
import { Modal, Checkbox, } from 'antd';
import * as Lodash from 'lodash';
import { AppStore} from '../../store';

const CheckboxGroup = Checkbox.Group;

interface IProps {
  appStore?: AppStore;
  plainOptions: any;
  visible: boolean,
  title: string,
  onCancel?(): any,
  onCreate?(values: any): any,
  // isClose: boolean
}
interface IState {
  checkedList: any,
  indeterminate: boolean,
  checkAll: boolean,
}

@inject("appStore")
@observer
class CheckModal extends React.Component<IProps, IState> {
  state: IState = {
    checkedList: [],
    indeterminate: false,
    checkAll: false
  };

  onChange = (checkedList: any) => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < this.props.plainOptions.length),
      checkAll: checkedList.length === this.props.plainOptions.length,
    });
  }

  onCheckAllChange = (e: any) => {
    const plainOptionsId: any = []
    this.props.plainOptions.map((item: any) => {
      plainOptionsId.push(item.value)
    })

    this.setState({
      checkedList: e.target.checked ? plainOptionsId : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  }

  onCreate = () => {
    const { checkedList } = this.state
    this.props.onCreate(checkedList)
    this.setState({
      checkedList: [],
      indeterminate: false,
      checkAll: false
    })
  }
  onCancel =() => {
    this.setState({
      checkedList: [],
      indeterminate: false,
      checkAll: false
    })
    this.props.onCancel();
  }

  render() {
    const { visible, title, plainOptions, } = this.props
    return (
      <div>
        {
          visible
          ? <Modal
            destroyOnClose
            title={title}
            visible={visible}
            onOk={this.onCreate}
            onCancel={this.onCancel}
            okText="确定"
            cancelText="取消"
          >
            <div style={{ borderBottom: '1px solid #E9E9E9' }}>
              <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                全选
              </Checkbox>
            </div>
            <br />
            <CheckboxGroup
              options={plainOptions}
              value={this.state.checkedList}
              onChange={this.onChange}
            />
          </Modal>
          : null
        }
      </div>
    )
  }
}

export default CheckModal;
